package com.quanyan.place.utils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.shiro.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Function;
import com.google.common.collect.Maps;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.utils.CommonUtils;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.place.entity.TbAcResource;

public class PlaceUtil {
	
	private final static Logger logger = LoggerFactory.getLogger(PlaceUtil.class);

	 /**
     *判断能否被除尽
     * @param amount 除数
     * @param count 被除数
     * @return
     */
    public static boolean check(double amount,int count){
        /*try {
            BigDecimal d = new BigDecimal(amount).divide(new BigDecimal(count));
            System.out.print(d);
        } catch (ArithmeticException e) {
            String msg = e.getMessage();
            if (msg.indexOf("Non-terminating") > -1) {
                System.out.println("Non-terminating");//无穷
                return false;
            }
        }*/
        //BigDecimal d = new BigDecimal(amount).divide(new BigDecimal(count));
        double d = amount/count;
        int a=String.valueOf(d).length();
        if (a>15) {
            return false;
        }
            return true;
    }
    
    /**
     * 判断入参比当前时间大
     * @param time
     * @return
     */
    public static  boolean compareTime(String time){
        SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        boolean result = false;
        try{
            Date createDate = sdf.parse(time);

            System.out.println(time+"===入参时间：" + createDate.getTime() + "--->当前时间：" + new Date().getTime());
            if (createDate.getTime() > new Date().getTime()){
                result = true;//显示
            }
        }catch(Exception ce){
            ce.printStackTrace();
        }
       return result;
    }
    
    /**
     *判断有几位小数
     * @param amount
     * @param count
     * @return
     */
    public static int checkNum(double amount,int count){
        double k=amount/count;
        String val=String.valueOf(k);
        int a=val.length();
        int b=val.indexOf(".");
        int y=a-(b+1);
        logger.info("小数位数"+y);
        return a-(b+1);
    }
    
    public static String createSalePlanId() {
        UUID randomUUID = UUID.randomUUID();
        String uuid = randomUUID.toString().replaceAll("-", "");
        StringBuffer bf = new StringBuffer();
        bf.append(uuid);
        return bf.toString().toLowerCase();
    }
    
    
    /**
     * 将字符串首次出现一位数字的地方前面填充0
     * @param content
     * @return
     */
    public static String placeUnitNameOperate(String content) {
        Pattern pattern = Pattern.compile("^\\d{1}$|^\\d{1}\\D|\\D\\d{1}\\D|\\D\\d{1}$");
        Matcher matcher = pattern.matcher(content);
        int count = 0;
        int key = 0;
        String value = "";
        while (matcher.find()) {
            if(count == 0){
                key = matcher.start();
                value = matcher.group();
                if(value.matches("^\\d{1}\\D")){
                    value = value.substring(0,1);
                    value = CommonUtils.zeroFill(value,2);
                    String contentPrefix = content.substring(0,key);
                    String contentSuffix = content.substring(key+1,content.length());
                    return contentPrefix + value + contentSuffix;
                }
                else if(value.matches("\\D\\d{1}\\D")){
                    value = value.substring(1,2);
                    value = CommonUtils.zeroFill(value,2);
                    String contentPrefix = content.substring(0,key+1);
                    String contentSuffix = content.substring(key+2,content.length());
                    return contentPrefix + value + contentSuffix;
                }
                else if(value.matches("^\\d{1}$")){
                    value = CommonUtils.zeroFill(value,2);
                    String contentPrefix = content.substring(0,key);
                    String contentSuffix = content.substring(key+1,content.length());
                    return contentPrefix + value + contentSuffix;
                }
                else if(value.matches("\\D\\d{1}$")){
                    value = value.substring(1,2);
                    value = CommonUtils.zeroFill(value,2);
                    String contentPrefix = content.substring(0,key+1);
                    String contentSuffix = content.substring(key+2,content.length());
                    return contentPrefix + value + contentSuffix;
                }
            }
            count++;
        }
       return content;
    }
    
    public static Date timeToDate(String time) {
        String dateTime = "2016-01-01 " + time;
        try {
            return DateUtils.strToDate(dateTime, DateUtils.DAY_DATE_FORMAT_HH_MM_SS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    
    /**
     * 检查一个数字是否在一个数组中出现
     *
     * @return
     */
    public static boolean checkNoInArray(byte no, String[] strs) {
        boolean flag = false;
        if (strs != null && strs.length > 0) {
            for (int i = 0; i < strs.length; i++) {
                Byte tempNo = Byte.valueOf(strs[i]);
                if (no == tempNo) {
                    flag = true;
                }
            }
        }
        return flag;
    }
    
    public static  List<Integer> splitIds(String joinedIds) {
        String[] ids = joinedIds.split(",");
        List<Integer> baseIds = new ArrayList<>();
        for (String id :ids) {
            baseIds.add(Integer.valueOf(id));
        }

        return baseIds;
    }

    public static  String joinIds(List<Integer> ids) {
        List<String> parts = new LinkedList<>();

        for (Integer id :ids) {
            parts.add(id.toString());
        }

        return StringUtil.join(",", parts);
    }

    public static int getTimeInterval(Byte minSaleTimeUnit) {
        // 按参数拆分时段
        if (null != minSaleTimeUnit && Constants.BYTE_ZERO == minSaleTimeUnit){
            // 半小时：30分钟
            return 30;
        } else {
            // 1小时：60分钟
            return 60;
        }
    }

    public static Date getMiddleTime(Date startTime) {
        String hms = DateUtils.transferHourDateToString(startTime);
        StringBuilder stringBuilder = new StringBuilder(hms);
        stringBuilder.replace(3, 5, "30");
        Date ret = DateUtils.tranferStringToDate(stringBuilder.toString(),DateUtils.DATE_FORMAT_HH_MM_SS);
        return ret;
    }
    
    public static List<TbAcResource>  convertToTree(List<TbAcResource> tbAcResourceList){
    	 List<TbAcResource>  result = new ArrayList<TbAcResource>();
    	 if (!CollectionUtils.isEmpty(tbAcResourceList)) {
 			Map<String,TbAcResource> map = Maps.uniqueIndex(tbAcResourceList, new Function<TbAcResource, String>() {
 				@Override
 				public String apply(TbAcResource input) {
 					return input.getCode();
 				}
 			});
 			
 			for (TbAcResource tbAcResource : tbAcResourceList) {
 				String  parentCode = tbAcResource.getParentCode();
 				TbAcResource parentResource = map.get(parentCode);
 				if (parentResource != null) {
 					parentResource.getChildren().add(tbAcResource);
 				} else {//为空即顶级菜单
 					result.add(tbAcResource);
 				}
 			}
 		}
    	return result;
    }

    /**
     * 生成入库，盘点编号
     * @param flag
     * @return
     */
    public static String getPlaceInventoryCode(String flag){
        //规则：I+8位年月日+5位随机编号，且保证入库单号全局唯一，如：I2017050887765
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String time = sdf.format(new Date());
        DecimalFormat df=new DecimalFormat("00000");
        String random = df.format(new Random().nextInt(100000)) + "";
        StringBuffer sb = new StringBuffer();
        String id = sb.append(flag).append(time).append(random).toString();
        return id;
    }
    
    /**
     * 判断是否是手机号
     * @param mobiles
     * @return
     */
   public static boolean isMobile(String mobiles){  
		Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");  
		Matcher m = p.matcher(mobiles);  
		return m.matches();  
   }

    public static BigDecimal isEmpty(BigDecimal a){
        if(a==null){
            return BigDecimal.ZERO;
        }
        return a;
    }
}
